package router

import (
	"gitee.com/igolang/pkg/boot"
	"gitee.com/igolang/pkg/xcfg"
	"gitee.com/igolang/pkg/xprom"
	"github.com/arl/statsviz"
	"github.com/gin-contrib/pprof"
	"github.com/gin-gonic/gin"
	"github.com/prometheus/client_golang/prometheus/promhttp"
	"net/http"
	"os"
	"path/filepath"
)

func debug(engine *gin.Engine) {
	prefix := xcfg.GetString("server.debugPrefix")
	if prefix == "" {
		prefix = "/debug"
	}
	group := engine.Group(prefix)
	group.GET("/env", func(ctx *gin.Context) {
		ctx.JSON(http.StatusOK, gin.H{
			"env":       xcfg.GetString("env"),
			"version":   boot.Info(),
			"d_version": os.Getenv("DVERSION"),
		})
	})

	if !xcfg.GetBool("server.monitoring") {
		return
	}
	pprof.RouteRegister(group)
	group.GET("/metrics", func(ctx *gin.Context) {
		handler := promhttp.Handler()
		if ctx.Query("f") == "json" {
			handler = xprom.JSONHandler()
		}
		handler.ServeHTTP(ctx.Writer, ctx.Request)
	})
	srv, _ := statsviz.NewServer(
		statsviz.Root(filepath.Join(group.BasePath(), "/debug/statsviz")),
	)
	ws := srv.Ws()
	index := srv.Index()
	group.GET("/debug/statsviz/*filepath", func(ctx *gin.Context) {
		if ctx.Param("filepath") == "/ws" {
			ws(ctx.Writer, ctx.Request)
			return
		}
		index(ctx.Writer, ctx.Request)
	})
}
